﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Syndication;
using System.Xml;
using System.Net;


namespace Friedlich.Web.RSS
{
    public class Aggregator
    {
        
        List<string> m_urls;

        public SyndicationFeed Feed
        {
            get { return Aggregate(Urls); }
        }

        public List<string> Urls
        {
            get { return m_urls; }
            set { m_urls = value; }
        }
        public Aggregator() {
            Urls = new List<string>();
        }
        public Aggregator(List<string> urls) {
            Urls = urls;
        }

        private SyndicationFeed Load(string url) {
            LiberalRss20FeedFormatter formatter = new LiberalRss20FeedFormatter();
            try
            
            {
                HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url); 
                httpRequest.MaximumAutomaticRedirections = 5;
                httpRequest.UserAgent = "Ropes.Services/1";
                XmlReader reader = XmlReader.Create(httpRequest.GetResponse().GetResponseStream());


                formatter.ReadFrom(reader);
            }
            catch (Exception)
            {
                                
            }
            
            
            return formatter.Feed;
         
        }
        private SyndicationFeed Aggregate(List<string> urls) {
            List<SyndicationItem> items = new List<SyndicationItem>();
            foreach (string url in urls) {
                SyndicationFeed metafeed = Load(url);
                if (metafeed != null && metafeed.Items != null)
                {
                    items.AddRange(metafeed.Items);
                }
            }
            //var items = from url in urls
            //            from item in Load(url).Items
            //            orderby item.PublishDate descending
            //            select item;
            SyndicationFeed feed = new SyndicationFeed(items.OrderByDescending<SyndicationItem,DateTimeOffset>(x=>x.PublishDate));
            return feed;
        }

     
    }
}
